package com.lipaluma.field.validator.impl.bool;

import java.lang.reflect.Field;

import com.lipaluma.annotations.validations.ValidateBoolean;
import com.lipaluma.context.Context;
import com.lipaluma.field.validator.impl.generic.AbstractConstantValidator;
import com.lipaluma.xml.validator.XmlConstantValidator;
import com.lipaluma.xml.validator.XmlValidator;

/**
 * Validate a boolean field to check if all value for the field is constant.<br/>
 * A value can be supplied or not. 
 * <ul>
 * <li>If the value is supplied, all values of the source must be equal to that value</li>
 * <li>If not, the first value encountered will be the constant to respect for all others.</li>
 * </ul>
 * 
 * <p>
 * To initialize :
 * <ul>
 * 	<li>
 * 	<u><b>By annotations :</b></u> Use {@link ValidateBoolean}, with the attribute <code>constant = true</code>. <br/>
 * To supply a value, put <code>constantSupplied = true</code> and the value supplied in <code>constantValue</code> attribute.<br/>
 * </li>
 * 	<li>
 * 	<u><b>By Xml :</b></u>
 * <ul>
 * <li>
 * See the example below to add a constant validator without supplied value : <br/>
 * <code>
 * &lt;ToMap field="..."   ...><br/>
 * &nbsp;&nbsp;&nbsp;<b>&lt;constant/></b><br/>
 * &lt;/ToMap>
 * </code>
 * <br/>
 * </li>
 * <li>
 * See this other example to add a constant validator with a supplied value : <br/>
 * <code>
 * &lt;ToMap field="..."   ...><br/>
 * &nbsp;&nbsp;&nbsp;<b>&lt;constant>true&lt;/constant></b><br/>
 * &lt;/ToMap>
 * </code>
 * <br/>
 * </li>
 * </li>
 * </ul>
 * @author Mario
 *
 */
public class BooleanConstantValidator extends AbstractConstantValidator<Boolean> {

	public BooleanConstantValidator() {}
	public BooleanConstantValidator(boolean value) {
		init(value);
	}
	
	@Override
	public boolean init(Context context, Field field) {
		ValidateBoolean annotation = field.getAnnotation(ValidateBoolean.class);
		if(annotation == null || !annotation.isConstant())
			return false;		
		if(annotation.constantSupplied()) {
			init(annotation.constantValue());
		}
		return true;
	}
	
	@Override
	public boolean init(Context context, Field field, XmlValidator xmlValidator) {
		XmlConstantValidator validator = (XmlConstantValidator) xmlValidator;
		if(validator.getConstantValue() != null)
			init(validator.getConstantValue(Boolean.class));
		return true;
	}	

}
